package pri.hillchen.springbootstd.sso.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 11:02 2017/11/29 0029.
 */
public class JWTUtil {

    private static final String SECRET = "XX#$%()(#*!()!KL<><MQLMNQNQJQK sdfkjsdrow32234545fdf>?N<:{LWPW";

    private static final String EXP = "exp";

    private static final String PAYLOAD = "payload";

    /**
     *加密，传入一个对象和有效期
     */

    public static <T> String sign(T object, long maxAge) {
        try {

            ObjectMapper mapper = new ObjectMapper();
            String jsonString = mapper.writeValueAsString(object);
            JwtBuilder builder = Jwts.builder()
                    .setPayload(jsonString)
                    .setExpiration(new Date(System.currentTimeMillis() + maxAge))
                    .signWith(SignatureAlgorithm.HS512, SECRET);
            return builder.compact();
        } catch(Exception e) {
            return null;
        }
    }

    //解密，传入一个加密后的token字符串和解密后的类型
    public static boolean parseJWT(String jwt) {
        return Jwts.parser().setSigningKey(SECRET).isSigned(jwt);
    }

    public static<T> String signByJti(T object,long jti) {
        try {

            ObjectMapper mapper = new ObjectMapper();
            String jsonString = mapper.writeValueAsString(object);
            JwtBuilder builder = Jwts.builder()
                    .setPayload(jsonString)
                    .setId(jti+"")
                    .setIssuedAt(new Date())
                    .signWith(SignatureAlgorithm.HS512, SECRET);
            return builder.compact();
        } catch(Exception e) {
            return null;
        }
    }
}
